package com.macro.mall.portal.service.impl;

import com.github.pagehelper.PageHelper;
import com.macro.mall.common.utils.DateUtil;
import com.macro.mall.dao.PmsProductDao;
import com.macro.mall.dao.PmsProductVertifyRecordDao;
import com.macro.mall.domain.*;
import com.macro.mall.mapper.*;
import com.macro.mall.model.*;
import com.macro.mall.portal.service.PmsProductService;
import com.macro.mall.portal.service.UmsMemberService;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 商品管理Service实现类
 * Created by macro on 2018/4/26.
 */
@Log4j2
@Service
@Transactional
public class PmsProductServiceImpl implements PmsProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PmsProductServiceImpl.class);
    @Autowired
    private PmsProductDao productDao;
    @Autowired
    private UmsMemberService memberService;
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsAlbumPicMapper pmsAlbumPicMapper;
    @Autowired
    private SmsHomeNewProductMapper newProductMapper;
    @Autowired
    private PmsProductVertifyRecordDao productVertifyRecordDao;
    @Autowired
    private PmsProductVertifyRecordMapper productVertifyRecordMapper;

    @Override
    public int create(CreateProductParam productParam) {
        UploadResult uploadResult = productParam.getUploadResult();
        int count;
        //创建商品
        PmsProduct product = productParam.getProductParam();
        product.setId(null);
        product.setDeleteStatus(0);
        product.setNewStatus(0);
        product.setPublishStatus(1);
        product.setVerifyStatus(0);
        product.setProductSn("" + System.currentTimeMillis());
        product.setCreateTime(new Date());
        product.setMemberId(product.getMemberId());
        log.info("商品新旧程度，{}", product.getQualityLevel());
        productMapper.insertSelective(product);
        List<PmsAlbumPicResult> files = uploadResult.getFiles();
        for (int i = 0; i < files.size(); i++) {
            PmsAlbumPicResult pmsAlbumPicResult = files.get(i);
            if (i == 0) {
                product.setPic(pmsAlbumPicResult.getPic());
                productMapper.updateByPrimaryKey(product);
            }
            pmsAlbumPicResult.setAlbumId(product.getId());
            pmsAlbumPicMapper.updateByPrimaryKey(pmsAlbumPicResult);
        }
        count = 1;
        return count;
    }

    private void handleSkuStockCode(List<PmsSkuStock> skuStockList, Long productId) {
        if (CollectionUtils.isEmpty(skuStockList)) return;
        for (int i = 0; i < skuStockList.size(); i++) {
            PmsSkuStock skuStock = skuStockList.get(i);
            if (StringUtils.isEmpty(skuStock.getSkuCode())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                //日期
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i + 1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }

    @Override
    public PmsProductResult getUpdateInfo(Long id) {
        return productDao.getUpdateInfo(id);
    }

    @Override
    public int update(Long id, PmsProduct product) {
        int count;
        //更新商品信息
        product.setId(id);
        productMapper.updateByPrimaryKeySelective(product);
        count = 1;
        return count;
    }

    @Override
    public List<PmsProduct> list(PmsProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) {

        PmsProductExample productExample = new PmsProductExample();
        PmsProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        if (productQueryParam.getId() != null) {
            criteria.andIdEqualTo(productQueryParam.getId());
        }
        if (productQueryParam.getPublishStatus() != null) {
            criteria.andPublishStatusEqualTo(productQueryParam.getPublishStatus());
        }
        if (productQueryParam.getVerifyStatus() != null) {
            criteria.andVerifyStatusEqualTo(productQueryParam.getVerifyStatus());
        }
        if (!StringUtils.isEmpty(productQueryParam.getKeyword())) {
            criteria.andNameLike("%" + productQueryParam.getKeyword() + "%");
        }
        if (productQueryParam.getProductCategoryName() != null) {
            criteria.andProductCategoryNameEqualTo(productQueryParam.getProductCategoryName());
        }
        if (productQueryParam.getMemberId() != null) {
            criteria.andMemberIdEqualTo(productQueryParam.getMemberId());
        }
        PageHelper.startPage(pageNum, pageSize);
        return productMapper.selectByExample(productExample);
    }

    @Override
    public int updateVerifyStatus(List<Long> ids, Integer verifyStatus, String detail) {
        PmsProduct product = new PmsProduct();
        product.setVerifyStatus(verifyStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        if (1 == verifyStatus) {
            for (Long id : ids) {
                PmsProduct pmsProduct = productMapper.selectByPrimaryKey(id);
                SmsHomeNewProduct smsHomeNewProduct = new SmsHomeNewProduct();
                smsHomeNewProduct.setProductId(id);
                smsHomeNewProduct.setProductName(pmsProduct.getName());
                smsHomeNewProduct.setRecommendStatus(1);
                smsHomeNewProduct.setRecommendDate(DateUtil.getTime());
                newProductMapper.insertSelective(smsHomeNewProduct);
                pmsProduct.setVerifyStatus(1);
                productMapper.updateByPrimaryKeySelective(pmsProduct);

                PmsProductVertifyRecordExample record = new PmsProductVertifyRecordExample();
                PmsProductVertifyRecordExample.Criteria criteria = record.createCriteria();
                criteria.andProductIdEqualTo(id);
                productVertifyRecordMapper.deleteByExample(record);
            }
        } else if (0 == verifyStatus) {
            for (Long id : ids) {
                SmsHomeNewProductExample smsHomeNewProductExample = new SmsHomeNewProductExample();
                SmsHomeNewProductExample.Criteria criteria = smsHomeNewProductExample.createCriteria();
                criteria.andProductIdEqualTo(id);
                List<SmsHomeNewProduct> smsHomeNewProducts = newProductMapper.selectByExample(smsHomeNewProductExample);
                if (null != smsHomeNewProducts) {
                    for (SmsHomeNewProduct newProduct : smsHomeNewProducts) {
                        newProductMapper.deleteByPrimaryKey(newProduct.getId());
                    }
                }
            }
        }else{
            List<PmsProductVertifyRecord> list = new ArrayList<>();
            for (Long id : ids) {
                PmsProductVertifyRecord record = new PmsProductVertifyRecord();
                record.setProductId(id);
                record.setCreateTime(new Date());
                record.setDetail(detail);
                record.setStatus(verifyStatus);
                list.add(record);
            }
            productVertifyRecordDao.insertList(list);
        }
        //修改完审核状态后插入审核记录
        return productMapper.updateByExample(product, example);
    }

    @Override
    public int updatePublishStatus(List<Long> ids, Integer publishStatus) {
        PmsProduct record = new PmsProduct();
        record.setPublishStatus(publishStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
        PmsProduct record = new PmsProduct();
        record.setRecommandStatus(recommendStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int updateNewStatus(List<Long> ids, Integer newStatus) {
        PmsProduct record = new PmsProduct();
        record.setNewStatus(newStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
        PmsProduct record = new PmsProduct();
        record.setDeleteStatus(deleteStatus);
        PmsProductExample example = new PmsProductExample();
        example.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(record, example);
    }

    @Override
    public List<PmsProduct> list(String keyword, Long memberId) {
        PmsProductExample productExample = new PmsProductExample();
        PmsProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        criteria.andMemberIdEqualTo(memberId);
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andNameLike("%" + keyword + "%");
            productExample.or().andDeleteStatusEqualTo(0).andProductSnLike("%" + keyword + "%");
        }
        return productMapper.selectByExample(productExample);
    }

    @Override
    public List<PmsProduct> getNewList() {
        return productDao.getNewList();
    }

    /**
     * @deprecated 旧版创建
     */
    public int createOld(PmsProductParam productParam) {
        int count;
        //创建商品
        PmsProduct product = productParam;
        product.setId(null);
        productMapper.insertSelective(product);
        count = 1;
        return count;
    }

    /**
     * 建立和插入关系表操作
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList(Object dao, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)) return;
            for (Object item : dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long) null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

}
